package com.sdkj.recruit.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.sdkj.recruit.dao.IShareDao;
import com.sdkj.recruit.dao.IUserDao;
import com.sdkj.recruit.model.FeedBack;
import com.sdkj.recruit.model.PlatformShare;
import com.sdkj.recruit.model.Praise;
import com.sdkj.recruit.model.ReleaseVersion;
import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.model.ShareComment;
import com.sdkj.recruit.model.ShareTimes;
import com.sdkj.recruit.model.User;
import com.sdkj.recruit.service.IShareService;
import com.sdkj.recruit.util.PropertiesUtil;
import com.sdkj.recruit.util.RandomUtil;
import com.sdkj.recruit.util.RequestContext;
import com.sdkj.recruit.util.StringUtil;
import com.sdkj.recruit.vo.FeedBackVo;
import com.sdkj.recruit.vo.PlatformShareVo;
import com.sdkj.recruit.vo.ReleaseVersionVo;
import com.sdkj.recruit.vo.ShareCommentVo;
import com.sdkj.recruit.vo.ShareTimesVo;

import net.sf.json.JSONObject;

@Service
public class ShareService implements IShareService {

	@Autowired
	private Mapper mapper;
	
	@Autowired
	private IShareDao shareDao;
	
	@Autowired
	private IUserDao userDao;
	
	private static final PropertiesUtil propertiesUtil = new PropertiesUtil("config.properties");

	private static final Logger logger =Logger.getLogger(ShareService.class);
	
	@Override
	public ResultData<Object> saveShare(ShareTimesVo showTimesVo) {
		ResultData<Object> result =new ResultData<>();
		String shareId =new RandomUtil().getRandomId();
		showTimesVo.setPublishType(1);
		ShareTimes st =mapper.map(showTimesVo, ShareTimes.class);
		st.setShareId(shareId);
		st.setShareTime(new Date());
		st.setShareStatus(0);
		shareDao.saveShare(st);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public ResultData<Object> deleteShare(String shareId) {
		
		ResultData<Object> result =new ResultData<>();
		shareDao.deleteShare(shareId);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public synchronized ResultData<Object>  praise(String userId, String shareId) {
		
		ResultData<Object> result =new ResultData<>();
		// 判断用户是否已经赞
		User user =userDao.queryUserById(userId);
		if(user==null){
			return ResultCode.error("用户不存在,不能点赞", null);
		}
		
		ShareTimes st =shareDao.querShareById(shareId);
		if(st ==null){
			return ResultCode.error("该分享已经不存在,不能点赞", null);
		}
		Praise p =shareDao.queryPraise(shareId,userId);
		// 没有赞过，增加赞
		if (p == null) {
			Praise ps = new Praise();
			ps.setPraiseTime(new Date());
			ps.setUserId(userId);
			ps.setShareId(shareId);
			shareDao.savePraise(ps);
			// 更新数量
			shareDao.updatePraiseCount(shareId, 1);
		}
		// 赞过，取消赞
		else {
			shareDao.deletePraise(shareId, userId);
			shareDao.updatePraiseCount(shareId, -1);
		}
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}


	@Override
	public ResultData<Object> querShareById(String shareId) {

		ResultData<Object> result = new ResultData<>();
		ShareTimes st = shareDao.querShareById(shareId);
		ShareTimesVo svo =mapperObj(st);
		
		logger.info("RequestContext.getUserId():"+RequestContext.getUserId());
		// 判断是否已经点赞
		if(!StringUtil.isEmptyString(RequestContext.getUserId())){
			Praise p =shareDao.queryPraise(st.getShareId(), RequestContext.getUserId());
			logger.info("p:"+p);
			if(p!=null){
				svo.setIsPraise(1);
			}
		}
		result.setObj(svo);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	private ShareTimesVo mapperObj(ShareTimes s) {
		
		ShareTimesVo sv =mapper.map(s, ShareTimesVo.class);
		User su = userDao.queryUserById(s.getUserId());
		if (su != null) {
			sv.setShareUserName(su.getNickName());
			sv.setShareUserPicId(su.getUserPicUrl());
		}
		List<ShareComment> commonVos =shareDao.queryCommonList(s.getShareId());
		List<ShareCommentVo> commonVosList =new ArrayList<>();
		if(!CollectionUtils.isEmpty(commonVos)){
			for(ShareComment sc :commonVos){
				ShareCommentVo vo =mapper.map(sc, ShareCommentVo.class);
				User scu = userDao.queryUserById(sc.getCommentUserId());
				if(scu!=null){
					vo.setCommentUserName(scu.getNickName());
				}
				commonVosList.add(vo);
			}
		}
		sv.setCommonVos(commonVosList);
		return sv;
	}

	@Override
	public ResultData<Object> shareList(int pageNo, int pageSize, String keyWord,int shareType,int queryType) {
		ResultData<Object> result =new ResultData<>();
		result.setObj(getCommonShareList(pageNo, pageSize, keyWord, shareType,queryType));
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public synchronized ResultData<Object> comment(ShareCommentVo shareCommentVo) {
		String commentId =new RandomUtil().getRandomId();
		ResultData<Object> result =new ResultData<>();
		ShareComment sc =mapper.map(shareCommentVo, ShareComment.class);
		sc.setCommentId(commentId);
		sc.setCommentTime(new Date());
		shareDao.comment(sc);
		// 增加评论数
		shareDao.updateCommentCount(shareCommentVo.getShareId(),1);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public long queryShareCount(String userId) {
		return shareDao.queryShareCount(userId);
	}

	@Override
	public ResultData<Object> getConfig() {

		ResultData<Object> result = new ResultData<>();
		String domain = propertiesUtil.getProperty("domain");
		JSONObject obj = new JSONObject();
		obj.put("domain", domain);
		result.setObj(obj);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	
	private List<ShareTimesVo> getCommonShareList (int pageNo, int pageSize, String keyWord,int shareType,int queryType){
		List<ShareTimes> stList =shareDao.shareList(pageNo,pageSize,keyWord,shareType,queryType);
		List<ShareTimesVo> stListVo =new ArrayList<>();
		if(!CollectionUtils.isEmpty(stList)){
			
			logger.info("RequestContext.getUserId():"+RequestContext.getUserId());
			
			for(ShareTimes s :stList){
				ShareTimesVo vo =mapperObjCommon(s);
				// 判断是否已经点赞
				if(!StringUtil.isEmptyString(RequestContext.getUserId())){
					Praise p =shareDao.queryPraise(s.getShareId(), RequestContext.getUserId());
					logger.info("p:"+p);
					if(p!=null){
						vo.setIsPraise(1);
					}
				}
				stListVo.add(vo);
			}
		}
		return stListVo;
	}
	private ShareTimesVo mapperObjCommon(ShareTimes s) {
		ShareTimesVo sv =mapper.map(s, ShareTimesVo.class);
		User su = userDao.queryUserById(s.getUserId());
		if (su != null) {
			sv.setShareUserName(su.getNickName());
			sv.setShareUserPicId(su.getUserPicUrl());
		}
		return sv;
	}

	@Override
	public List<ShareTimesVo> queryShareList(int pageNo, int pageSize, String content,int shareType,String nickName,String shareStartDate,String shareEndDate) {
		List<ShareTimes> stList =shareDao.queryShareList(pageNo,pageSize,content,shareType,nickName,shareStartDate,shareEndDate);
		List<ShareTimesVo> stListVo =new ArrayList<>();
		if(!CollectionUtils.isEmpty(stList)){
			for(ShareTimes s :stList){
				ShareTimesVo vo =mapperObjCommon(s);
				// 判断是否已经点赞
				Praise p =shareDao.queryPraise(s.getShareId(), RequestContext.getUserId());
				if(p!=null){
					vo.setIsPraise(1);
				}
				stListVo.add(vo);
			}
		}
		return stListVo;
		
	}

	@Override
	public long queryAllUserCount(String content, int shareType, String nickName, String shareStartDate, String shareEndDate) {
		return shareDao.queryAllUserCount(content,shareType,nickName,shareStartDate,shareEndDate);
	}

	@Override
	public ResultData<Object> shield(String shareId,int optType) {
		
		ResultData<Object> result = new ResultData<>();
		Map<String, Object> property =new HashMap<String, Object>();
		property.put("shareStatus", optType);
		shareDao.updateShare(property,shareId);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public synchronized ResultData<Object> deleteComment(ShareCommentVo shareCommentVo) {
		shareDao.deleteComment(shareCommentVo.getShareId(),shareCommentVo.getCommentId());
		// 数量更新
		shareDao.updateCommentCount(shareCommentVo.getShareId(), -1);
		return ResultCode.success("删除评论成功", null);
	}

	@Override
	public ResultData<Object> userShareList(int pageNo, int pageSize, String userId, int queryType) {
		ResultData<Object> result = new ResultData<>();
		List<ShareTimes> stList = null;
		// 查询自己的 分享或回复
		/*if (userId.equals(RequestContext.getUserId())) {

			if (queryType == 1) {
				stList = shareDao.shareList(pageNo, pageSize, userId);
			}
			if (queryType == 2) {
				// 获取自己回复的列表
				List<ShareComment> list = shareDao.queryCommonListByUserId(userId);
				List<String> shareIds = new ArrayList<>();
				if (!CollectionUtils.isEmpty(list)) {
					for (ShareComment sc : list) {
						if (!shareIds.contains(sc.getShareId())) {
							shareIds.add(sc.getShareId());
						}
					}
				}
				stList = shareDao.shareList(pageNo, pageSize, shareIds);
			}

		}*/
		
		if (queryType == 1) {
			stList = shareDao.shareList(pageNo, pageSize, userId);
		}
		if (queryType == 2) {
			// 获取自己回复的列表
			List<ShareComment> list = shareDao.queryCommonListByUserId(userId);
			List<String> shareIds = new ArrayList<>();
			if (!CollectionUtils.isEmpty(list)) {
				for (ShareComment sc : list) {
					if (!shareIds.contains(sc.getShareId())) {
						shareIds.add(sc.getShareId());
					}
				}
			}
			stList = shareDao.shareList(pageNo, pageSize, shareIds);
		}
		
		// 查询别人分享的
		else {
			stList = shareDao.shareList(pageNo, pageSize, userId);
		}

		logger.info("RequestContext.getUserId():"+RequestContext.getUserId());

		
		List<ShareTimesVo> stListVo = new ArrayList<>();
		if (!CollectionUtils.isEmpty(stList)) {
			for (ShareTimes s : stList) {
				ShareTimesVo vo = mapperObjCommon(s);
				// 判断是否已经点赞
				if(!StringUtil.isEmptyString(RequestContext.getUserId())){
					Praise p =shareDao.queryPraise(s.getShareId(), RequestContext.getUserId());
					logger.info("p:"+p);
					if(p!=null){
						vo.setIsPraise(1);
					}
				}
				stListVo.add(vo);
			}
		}
		result.setObj(stListVo);
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	@Override
	public ResultData<Object> feedback(FeedBackVo feedBackVo) {
		String feedBackId =new RandomUtil().getRandomId();

		feedBackVo.setFeedBackId(feedBackId);
		feedBackVo.setFeedBackDate(new Date());
		shareDao.feedback(mapper.map(feedBackVo, FeedBack.class));
		return ResultCode.success("反馈成功",feedBackVo);
	}

	@Override
	public ResultData<Object> platformShare(PlatformShareVo platformShareVo) {
		
		String platformShareId =new RandomUtil().getRandomId();
		platformShareVo.setPlatformShareId(platformShareId);
		platformShareVo.setPlatformShareDate(new Date());
		shareDao.platformShare(mapper.map(platformShareVo, PlatformShare.class));
		
		shareDao.updateShareCount(platformShareVo.getShareId(), 1);
		return ResultCode.success("分享成功",platformShareVo);
	}

	@Override
	public ResultData<Object> autoUpdate() {
		ReleaseVersion auto =shareDao.autoUpdate();
		return ResultCode.success("获取版本更新成功",mapper.map(auto, ReleaseVersionVo.class));
	}

	@Override
	public ResultData<Object> increaseReadCount(String shareId) {
		shareDao.increaseReadCount(shareId);
		return ResultCode.success("更新阅读量成功",null);
	}

	@Override
	public ResultData<Object> edit(ShareTimesVo showTimesVo) {
		if(StringUtil.isEmptyString(showTimesVo.getShareId())){
			return ResultCode.error("修改失败，主键不能为空", null);
		}
		
		Map<String, Object> property =new HashMap<>();
		if(showTimesVo.getCommentCount()>0){
			property.put("commentCount", showTimesVo.getCommentCount());
		}
		
		if(showTimesVo.getReadCount()>0){
			property.put("readCount", showTimesVo.getReadCount());
		}
		
		if(showTimesVo.getPraiseCount()>0){
			property.put("praiseCount", showTimesVo.getPraiseCount());
		}
		
		if(showTimesVo.getShareCount()>0){
			property.put("shareCount", showTimesVo.getShareCount());
		}
		shareDao.updateShare(property, showTimesVo.getShareId());
		return ResultCode.success("修改成功", null);
	}

	@Override
	public ResultData<Object> increasePraiseCount(String shareId) {
		// 更新数量
		shareDao.updatePraiseCount(shareId, 1);
		return ResultCode.success("修改成功", null);
	}

	@Override
	public List<ShareTimes> shareList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public  void increasePraiseCount(String shareId, int count) {
		// TODO Auto-generated method stub
		// 更新数量
		shareDao.updatePraiseCount(shareId, count);
	}

	@Override
	public  void increaseReadCount(String shareId, int count) {
		// TODO Auto-generated method stub
		shareDao.increaseReadCount(shareId,count);

	}

}
